import strHtml from "./MarketPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { productService } from "../../services/productService";

export class MarketPage {
  constructor() {
    this.dom = null;
    this.productList = [];
  }

  async render() {
    this.dom = DomUtils.convertToDom(strHtml);
    await this._loadData();
    this._renderCategoryOptions();
    this._bindEvents();
    const onSaleProducts = this.productList.filter((p) => p.status === "上架");
    this._renderProductList(onSaleProducts);
    return this.dom;
  }

  async _loadData() {
    try {
      const response = await productService.getAll();
      console.log("商城加载商品数据:", response);
      this.productList = response;

      // 记录初始库存（只记录一次）
      this.productList.forEach((p) => {
        const key = "initialStock_" + p.productId;
        if (!localStorage.getItem(key)) {
          localStorage.setItem(key, p.stock);
        }
      });
    } catch (error) {
      console.error("加载商品数据失败:", error);
      this.productList = [];
    }
  }

  _renderCategoryOptions() {
    const categorySelect = this.dom.querySelector("#filter-category");
    categorySelect.innerHTML = '<option value="">全部</option>';
    const categories = Array.from(
      new Set(
        this.productList
          .filter((p) => p.status === "上架")
          .map((p) => p.category)
      )
    ).filter(Boolean);

    categories.forEach((cat) => {
      const option = document.createElement("option");
      option.value = cat;
      let displayName = cat;
      if (cat === "fruit") displayName = "水果";
      if (cat === "vegetable") displayName = "蔬菜";
      option.textContent = displayName;
      categorySelect.appendChild(option);
    });
  }

  _bindEvents() {
    this.dom
      .querySelector("#filter-category")
      .addEventListener("change", (e) => {
        const category = e.target.value;
        const onSaleProducts = this.productList.filter(
          (p) => p.status === "上架"
        );
        const filtered = category
          ? onSaleProducts.filter((p) => p.category === category)
          : onSaleProducts;
        this._renderProductList(filtered);
      });

    this.dom.querySelector("#filter-price").addEventListener("change", (e) => {
      const order = e.target.value;
      const onSaleProducts = this.productList.filter(
        (p) => p.status === "上架"
      );
      const sorted = [...onSaleProducts];
      if (order === "asc") {
        sorted.sort((a, b) => (a.productPrice || 0) - (b.productPrice || 0));
      } else if (order === "desc") {
        sorted.sort((a, b) => (b.productPrice || 0) - (a.productPrice || 0));
      }
      this._renderProductList(sorted);
    });

    this.dom.querySelector("#search-btn").addEventListener("click", () => {
      const keyword = this.dom
        .querySelector("#search-input")
        .value.toLowerCase();
      const onSaleProducts = this.productList.filter(
        (p) => p.status === "上架"
      );
      const filtered = onSaleProducts.filter(
        (p) =>
          (p.productName && p.productName.toLowerCase().includes(keyword)) ||
          (p.category && p.category.toLowerCase().includes(keyword))
      );
      this._renderProductList(filtered);
    });
  }

  _renderProductList(products) {
    const container = this.dom.querySelector("#product-list");
    container.innerHTML = "";

    if (products.length === 0) {
      container.innerHTML =
        '<div class="col-12 text-center"><p class="text-muted">暂无商品</p></div>';
      return;
    }

    // === 推荐商品计算逻辑 ===
    const maxClick = Math.max(...products.map((p) => p.clickCount || 0));
    let bestProductId = null;
    let bestScore = -1;

    products.forEach((p) => {
      const initialStock =
        parseInt(localStorage.getItem("initialStock_" + p.productId)) ||
        p.stock ||
        1;
      const stockRatio = 1 - p.stock / initialStock;
      const clickRatio = maxClick ? (p.clickCount || 0) / maxClick : 0;
      const score = 0.7 * stockRatio + 0.3 * clickRatio;

      if (score > bestScore) {
        bestScore = score;
        bestProductId = p.productId;
      }
    });

    // === 商品卡片渲染 ===
    products.forEach((product) => {
      const card = document.createElement("div");
      card.className = "col-md-4 mb-4";
      card.innerHTML = `
        <div class="card h-100">
          <img src="${
            product.productImageUrl || ""
          }" class="card-img-top" alt="${
        product.productName || "商品图片"
      }" style="height: 200px; object-fit: cover;">
          <div class="card-body d-flex flex-column">
            <h5 class="card-title d-flex justify-content-between align-items-center">
              <span>${product.productName || "未命名商品"}</span>
              ${
                product.productId === bestProductId
                  ? '<span class="badge bg-warning text-dark ms-2">人气推荐</span>'
                  : ""
              }
            </h5>
            <p class="card-text text-muted small">
              产地：${product.productionPlace || "未知"}<br>
              生产日期：${product.productionDate || "未知"}<br>
              生长周期：${product.productionPeriod || "未知"}
            </p>
            <div class="d-flex justify-content-between align-items-center mb-2">
              <p class="card-text text-primary fw-bold mb-0">￥${(
                product.productPrice || 0
              ).toFixed(2)}</p>
              <span class="badge ${
                product.stock > 0 ? "bg-success" : "bg-danger"
              }">
                ${product.stock > 0 ? `库存: ${product.stock}` : "已售罄"}
              </span>
            </div>
            <button class="btn btn-outline-success mt-2 add-to-cart-btn" data-id="${
              product.productId
            }" ${product.stock <= 0 ? "disabled" : ""}>加入购物车</button>
          </div>
        </div>
      `;

      card.querySelector(".add-to-cart-btn").addEventListener("click", (e) => {
        e.stopPropagation();
        this._addToCart(product);
      });

      card.addEventListener("click", () => {
        localStorage.setItem("selectedProduct", JSON.stringify(product));
        location.hash = "#/product-detail";
      });

      container.appendChild(card);
    });
  }

  _addToCart(product) {
    const cart = JSON.parse(localStorage.getItem("cart") || "[]");
    const existing = cart.find((p) => p.productId === product.productId);
    if (existing) {
      if (existing.quantity < product.stock) {
        existing.quantity += 1;
      } else {
        alert("已达库存上限，无法继续添加！");
        return;
      }
    } else {
      if (product.stock > 0) {
        cart.push({ ...product, quantity: 1 });
      } else {
        alert("该商品已售罄，无法添加！");
        return;
      }
    }
    localStorage.setItem("cart", JSON.stringify(cart));
    alert("已添加到购物车！");
  }
}
